import * as Sequelize from 'sequelize';
import { DataTypes, Model, Optional } from 'sequelize';

export interface UserAttributes {
  userId: string;
  userName?: string;
  deviceId?: string;
  phone?: string;
  password?: string;
  roleId?: string;
  userImg?: string;
  createdTime: Date;
  updatedTime: Date;
  userAgent?: string;
}

export type UserPk = 'userId';
export type UserId = User[UserPk];
export type UserOptionalAttributes =
  | 'userName'
  | 'deviceId'
  | 'phone'
  | 'password'
  | 'roleId'
  | 'userImg'
  | 'createdTime'
  | 'updatedTime'
  | 'userAgent';
export type UserCreationAttributes = Optional<
  UserAttributes,
  UserOptionalAttributes
>;

export class User
  extends Model<UserAttributes, UserCreationAttributes>
  implements UserAttributes
{
  userId!: string;
  userName?: string;
  deviceId?: string;
  phone?: string;
  password?: string;
  roleId?: string;
  userImg?: string;
  createdTime!: Date;
  updatedTime!: Date;
  userAgent?: string;

  static initModel(sequelize: Sequelize.Sequelize): typeof User {
    return User.init(
      {
        userId: {
          type: DataTypes.CHAR(36),
          allowNull: false,
          primaryKey: true,
          field: 'user_id',
        },
        userName: {
          type: DataTypes.STRING(255),
          allowNull: true,
          field: 'user_name',
        },
        deviceId: {
          type: DataTypes.STRING(32),
          allowNull: true,
          field: 'device_id',
        },
        phone: {
          type: DataTypes.STRING(255),
          allowNull: true,
        },
        password: {
          type: DataTypes.STRING(255),
          allowNull: true,
        },
        roleId: {
          type: DataTypes.STRING(20),
          allowNull: true,
          field: 'role_id',
        },
        userImg: {
          type: DataTypes.STRING(255),
          allowNull: true,
          field: 'user_img',
        },
        createdTime: {
          type: DataTypes.DATE,
          allowNull: false,
          defaultValue: Sequelize.Sequelize.literal('CURRENT_TIMESTAMP'),
          comment: '创建时间',
          field: 'created_time',
        },
        updatedTime: {
          type: DataTypes.DATE,
          allowNull: false,
          defaultValue: Sequelize.Sequelize.literal('CURRENT_TIMESTAMP'),
          comment: '更新时间',
          field: 'updated_time',
        },
        userAgent: {
          type: DataTypes.STRING(255),
          allowNull: true,
          comment: '用户浏览器信息',
          field: 'user_agent',
        },
      },
      {
        sequelize,
        tableName: 'user',
        timestamps: false,
        indexes: [
          {
            name: 'PRIMARY',
            unique: true,
            using: 'BTREE',
            fields: [{ name: 'user_id' }],
          },
          {
            name: 'idx_user_id',
            using: 'BTREE',
            fields: [{ name: 'user_id' }],
          },
        ],
      },
    );
  }
}
